<template>
  <div>
    <div v-if="props.userId">
      <div class="openResult">
        <el-result v-if="open === 0" icon="info" title="链接中..." />
        <el-result v-if="open === 1" icon="error" title="链接失败...">
          <template #extra>
            <el-button @click="reload" type="primary">刷新</el-button>
          </template>
        </el-result>
      </div>
      <div v-if="open === 2" class="chat-container">
        <!-- 聊天记录区域 -->
        <div class="chat-messages" ref="messageContainer">
          <div v-if="list.length > 0">
            <div
              v-for="msg in list"
              :key="msg.createTime"
              :class="[
                'message-item',
                msg.role === 'assistant' ? 'message-right' : 'message-left',
              ]"
            >
              <el-avatar :size="40" :src="getAvatarUrl(msg.role)" />
              <div class="message-content">
                <p class="nickname">
                  {{ msg.role === "assistant" ? "客服" : "访客" }}
                </p>
                <div class="message-text">{{ msg.content }}</div>
                <span class="message-time">{{ msg.createTime }}</span>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无消息" />
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-area">
          <!-- 功能按钮区 -->
          <div class="toolbar">
            <div class="left-tools">
              <el-popover
                placement="top-start"
                :width="420"
                trigger="click"
                popper-class="emoji-popover"
                :teleported="true"
                :append-to-body="true"
                :z-index="10000"
                :offset="12"
              >
                <template #reference>
                  <el-button class="tool-btn" text> 😊 </el-button>
                </template>
                <div class="emoji-container">
                  <span
                    v-for="emoji in emojiList"
                    :key="emoji"
                    class="emoji-item"
                    @click="insertEmoji(emoji)"
                  >
                    {{ emoji }}
                  </span>
                </div>
              </el-popover>

              <el-button class="tool-btn" text title="视频通话">
                <el-icon><VideoCamera /></el-icon>
              </el-button>

              <el-button class="tool-btn" text title="语音通话">
                <el-icon><Microphone /></el-icon>
              </el-button>

              <el-popover
                  placement="top-start"
                  :width="420"
                  :max-height="300"
                  trigger="click"
                  popper-class="emoji-popover"
                  :teleported="true"
                  :append-to-body="true"
                  :z-index="10000"
                  :offset="12"
              >
                <template #reference>
                  <el-button class="tool-btn" text title="常用语" @click="showCommonStatements">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </template>
                <div class="phrase-container">
                  <span
                      v-for="stmt in commonStatements"
                      :key="stmt.id"
                      class="phrase-item"
                      @click="insertCommonStatement(stmt.statement)"
                  >
                    {{ stmt.statement }}
                  </span>
                </div>
              </el-popover>
            </div>
          </div>

          <!-- 输入框和发送按钮 -->
          <div class="input-wrapper">
            <el-input
              v-model="message"
              type="textarea"
              :rows="3"
              placeholder="请输入消息..."
              resize="none"
              class="message-input"
              @keyup.enter.ctrl="sendMessage"
            />
            <el-button
              type="primary"
              class="send-btn"
              :disabled="!message.trim()"
              @click="sendMessage"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="chat-container">
      <el-result icon="warning" title="请选择访客" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch, onMounted } from "vue";
import { emojiList } from "@/constants/emojis";
import { useUserStore } from "@/store/modules/user";
import { saveMessage } from "@/api/message";
import { ElMessage } from 'element-plus'
import request from "@/utils/request";
import { getUserInfoApi } from "@/api/user";
import { queryChatDetail } from "@/api/chat";

interface CommonStatement {
  id: number;
  statement: string;
}

const currentUserUsername = ref<string>('');
onMounted(() => {
  getUserInfoApi().then(res => {
    currentUserUsername.value = res.data.username || '';
    showCommonStatements();
  }).catch(() => {
    ElMessage.error('获取当前用户信息失败，请重试');
  });
});

// 常用语列表状态
const commonStatements = ref<CommonStatement[]>([]);

// 对话框显示状态
const dialogVisible = ref(false);

// 显示常用语列表的方法
const showCommonStatements = async () => {
  try {
    // 调用后端API获取常用语列表
    const response = await request.post('/api/v1/statement/searchStatement', {
      pageSize: 1000, // 确保发送的请求体中包含pageSize属性
      pageNo: 1, // 可以添加其他必要的查询参数
      createBy: currentUserUsername.value // 添加当前登录用户名
    });
    commonStatements.value = response.data.list;
    dialogVisible.value = true; // 显示对话框
  } catch (error) {
    console.error('获取常用语失败:', error);
    ElMessage.error('获取常用语失败，请重试');
  }
};

// 选择常用语并填充到输入框的方法
const insertCommonStatement = (statement: string) => {
  message.value += statement; // 将常用语追加到原来的文字后面
  dialogVisible.value = false; // 选择后关闭对话框
};

// 获取用户 store
const userStore = useUserStore();

interface Message {
  id?: number;
  role: string;
  content: string;
  createTime: string;
}

// 确保正确定义 props
const props = defineProps<{ userId: string }>();

const userId = userStore.user.userId;
const list = ref<Message[]>([]);
const open = ref(0);
const message = ref("");
const users = ref([]);
const emit = defineEmits(["update-users", "update-chat", "highlight-visitor"]); // 合并事件定义
const currentToUser = ref("2be85d7d4263c1373972c779acb82bab"); // 示例访客ID
const customersData = ref([]);
let pageNum = ref(1);
const pageSize = 10;
let loadingMore = ref(false);

let ws: any = null;

// 插入表情
const insertEmoji = (emoji: string) => {
  message.value += emoji;
};

// 获取头像 URL
const getAvatarUrl = (role: string) => {
  return role === "assistant"
    ? "https://qy-kefu.oss-cn-beijing.aliyuncs.com/img/客服.png"
    : "https://qy-kefu.oss-cn-beijing.aliyuncs.com/img/客户来访.png";
};

// WebSocket连接
const connectWebSocket = () => {
  console.log("=== WebSocket连接开始 ===");
  const deptId = userStore.user.deptId;
  console.log("连接的公司ID:", deptId);
  const wsUrl = `ws://localhost:9090/api/v1/chat/${userId}/${deptId}`;
  console.log("连接地址:", wsUrl);

  ws = new WebSocket(wsUrl);

  ws.onopen = () => {
    console.log("=== WebSocket连接成功 ===");
    console.log("连接状态:", ws.readyState);
    open.value = 2;
  };

  ws.onerror = (error: Event) => {
    console.error("=== WebSocket连接错误 ===");
    console.error("错误信息:", JSON.stringify(error, null, 2));
    open.value = 1;
  };

  ws.onclose = (event: CloseEvent) => {
    console.log("=== WebSocket连接关闭 ===");
    console.log(
      "关闭信息:",
      JSON.stringify(
        {
          code: event.code,
          reason: event.reason,
          wasClean: event.wasClean,
        },
        null,
        2
      )
    );

    // 显示关闭原因
    ElMessage.error(`聊天已断开: ${event.reason}`);
  };

  ws.onmessage = async (e: MessageEvent) => {
    console.log("=== 收到WebSocket消息 ===");
    try {
      const rawData = e.data;
      const data = JSON.parse(rawData);
      console.log("+++++++++++++++++");
      console.log(data);

      if (data.companyId && data.users) {
        const userList = data.users.map((user: any) => ({
          username: user.username,
          lastTime: new Date().toLocaleTimeString(),
          status: "online",
          unreadCount: user.unreadCount,
        }));

        console.log(
          "用户列表更新:",
          JSON.stringify(
            {
              users: userList,
              timestamp: new Date().toISOString(),
            },
            null,
            2
          )
        );

        users.value = userList;
        emit("update-users", users.value);
      }

      if (data.content != null) {
        const isRelevantMessage =
          data.fromUserName === currentToUser.value ||
          data.toUserName === currentToUser.value ||
          data.toUserName === userId;

        if (isRelevantMessage) {
          list.value.push(data);
          console.log("___________________");
          console.log(data);
          if (data.fromUserName == selectedUser.username) {
            console.log("vvvvvvvvvvvvvvvvvvvvvvvvvv");

            // 调用更新消息状态的接口
            try {
              await request.put(`/api/v1/message/updateStatus/${data.fromUserName}`);
            } catch (error) {
              console.error("更新消息状态失败:", error);
            }
          }

          nextTick(() => {
            const messageSound = new Audio("/message.mp3");
            messageSound.play();
            scrollToBottom();
          });
        }
      }
    } catch (error: any) {
      console.error(
        "消息处理错误:",
        JSON.stringify(
          {
            error: error.message,
            rawData: e.data,
            timestamp: new Date().toISOString(),
          },
          null,
          2
        )
      );
    }
  };
};

// 监听用户ID变化
watch(
  () => props.userId,
  (newUserId) => {
    console.log(
      "用户切换:",
      JSON.stringify(
        {
          type: "user_switch",
          previousUser: currentToUser.value,
          newUser: newUserId,
          timestamp: new Date().toISOString(),
        },
        null,
        2
      )
    );

    if (newUserId) {
      currentToUser.value = newUserId;
      list.value = [];
      message.value = "";
      pageNum.value = 1;

      if (!ws || ws.readyState !== WebSocket.OPEN) {
        connectWebSocket();
      }
    }
  }
);

// 发送消息
const sendMessage = () => {
  const content = message.value.trim();
  if (!content) {
    console.warn(
      "发送取消:",
      JSON.stringify(
        {
          reason: "empty_content",
          timestamp: new Date().toISOString(),
        },
        null,
        2
      )
    );
    return;
  }

  const messageData = {
    fromUserName: userStore.user.userId,
    toUserName: currentToUser.value,
    role: "assistant",
    content: content,
    companyId: userStore.user.deptId,
    createTime: new Date().toISOString(),
  };

  console.log(
    "准备发送:",
    JSON.stringify(
      {
        type: "chat_message",
        data: messageData,
        wsState: ws?.readyState,
        timestamp: new Date().toISOString(),
      },
      null,
      2
    )
  );

  if (ws?.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify(messageData));

    // 调用保存接口
      
    saveMessage(messageData);

    list.value.push({
      role: "assistant",
      content: content,
    });

    console.log(
      "发送成功:",
      JSON.stringify(
        {
          messageData,
          currentList: list.value,
          timestamp: new Date().toISOString(),
        },
        null,
        2
      )
    );

    message.value = "";
    scrollToBottom();
  } else {
    console.error(
      "发送失败:",
      JSON.stringify(
        {
          reason: "websocket_not_connected",
          wsState: ws?.readyState,
          messageData,
          timestamp: new Date().toISOString(),
        },
        null,
        2
      )
    );
  }
};

// ·滚动到当前进度往下一点
const scrollToBottom = () => {
  nextTick(() => {
    const container = document.querySelector(".chat-messages");
    if (container) {
      // 获取当前的 scrollTop 值
      const currentScrollTop = container.scrollTop;
      // 向下滚动一点，例如 50 像素
      const scrollOffset = 50; // 可以根据需要调整这个值
      container.scrollTop = currentScrollTop + scrollOffset; // 在当前基础上向下滚动
    }
  });
};

// 在更新聊天记录后调用
watch(list, () => {
  scrollToBottom(); // 调用滚动函数
});

// 页面加载
onMounted(() => {
  connectWebSocket();
});

const loadChatHistory = async (append = false) => {
  if (loadingMore.value) return; // 防止重复加载
  loadingMore.value = true;
  try {
    const response = await queryChatDetail(currentToUser.value, pageNum.value, pageSize);
    const newMessages = response.data.list.map((msg) => ({
      role: msg.senderType === 0 ? "visitor" : "assistant",
      content: msg.message,
      createTime: msg.createTime,
    }));

    // 反转聊天记录并更新到 list
    const reversedMessages = newMessages.reverse();
    console.log("获取到的聊天记录:", reversedMessages);

    if (append) {
      list.value = [...reversedMessages, ...list.value]; // 追加新消息
    } else {
      list.value = reversedMessages; // 替换消息
    }
  } catch (error) {
    console.error("加载聊天记录失败:", error);
  } finally {
    loadingMore.value = false; // 重置加载状态
  }
};



// 监听用户ID变化
watch(() => props.userId, (newUserId) => {
  if (newUserId) {
    currentToUser.value = newUserId;
    list.value = [];
    message.value = "";
    loadChatHistory();
    console.log("_______________________________");
    pageNum.value = 1;

    nextTick(() => {
      const messageContainer = document.querySelector(".chat-messages");
      if (messageContainer) {
        messageContainer.addEventListener("scroll", handleScroll);
      } else {
        console.error("未找到 .chat-messages 元素");
      }
    });
  }
});

watch(() => props.userId, (newUserId) => {
  console.log("加载历史数据");
  if (newUserId) {
    currentToUser.value = newUserId;
    loadChatHistory();
  }
});

const handleScroll = (event) => {
  const container = event.target;
  if (container.scrollTop === 0 && !loadingMore.value) {
    console.log("滚动到顶部，加载更多消息...");
    pageNum.value += 1; // 增加页码
    loadChatHistory(true); // 加载更多消息
  }
};
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 86px);
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background-color: #f5f7fa;
    height: 400px;

    .message-item {
      display: flex;
      margin-bottom: 20px;
      gap: 12px;

      .message-content {
        max-width: 60%;
      }

      .nickname {
        font-size: 12px;
        color: #909399;
        margin-bottom: 4px;
      }

      .message-text {
        padding: 10px 16px;
        border-radius: 12px;
        background: #fff;
        word-break: break-all;
        line-height: 1.4;
      }

      .message-time {
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
        display: block;
      }
    }

    .message-left {
      justify-content: flex-start;

      .nickname {
        text-align: left;
      }
    }

    .message-right {
      flex-direction: row-reverse;

      .message-text {
        background: #409EFF;
        color: #fff;
      }

      .nickname,
      .message-time {
        text-align: right;
      }
    }
  }

  .chat-input-area {
    border-top: 1px solid #dcdfe6;
    padding: 15px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    gap: 10px;

    .toolbar {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;

      .left-tools {
        display: flex;
        gap: 8px;
        align-items: center;

        .tool-btn {
          font-size: 20px !important;
          padding: 8px !important;
          height: auto !important;
          color: #606266;

          .el-icon {
            font-size: 20px;
          }

          &:hover {
            color: #409EFF;
            background-color: #ecf5ff;
          }
        }
      }
    }

    .input-wrapper {
      display: flex;
      align-items: center;
      width: 100%;
      position: relative;
      margin-top: 12px;

      .message-input {
        flex: 1;
        width: 0;

        :deep(.el-textarea__inner) {
          border-radius: 4px;
          resize: none;
          font-size: 14px;
          padding: 8px 12px;
          border: 1px solid #dcdfe6;
          transition: border-color 0.3s;

          &:focus {
            border-color: #409EFF;
            box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
          }
        }
      }

      .send-btn {
        position: absolute;
        right: 10px;
        bottom: 10px;
        padding: 8px 16px;
        font-size: 14px;
        border-radius: 4px;
        background-color: #409EFF;
        color: #fff;
        transition: background-color 0.3s;

        &:hover {
          background-color: #66b1ff;
        }
      }
    }
  }
}

.phrase-container {
  overflow-y: auto;
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
  padding: 12px;
  text-align: left;
}

.phrase-item {
  cursor: pointer;
  padding-left: 6px;
  font-size: 12px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  border-radius: 4px;
  transition: all 0.2s;
  background-color: #f9f9f9;
  &:hover {
    background: #f5f7fa;
    transform: scale(1.05);
  }
}

.emoji-container {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  padding: 12px;

  .emoji-item {
    cursor: pointer;
    font-size: 24px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    transition: all 0.2s;

    &:hover {
      background: #f5f7fa;
      transform: scale(1.1);
    }
  }
}

:deep(.emoji-popover) {
  padding: 0;
  z-index: 10000 !important;
}

.message-left {
  justify-content: flex-start;

  .nickname {
    text-align: left;
  }
}

.message-right {
  flex-direction: row-reverse;

  .message-text {
    background: #409eff;
    color: #fff;
  }

  .nickname,
  .message-time {
    text-align: right;
  }
}
</style>
